package com.wugh.fast.security.social.app.qq.api;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

/**
 * 说明: QQ授权认证的默认实现
 *
 * @author wugh
 * @date 2018-09-13 14:46
 */
@Slf4j
public class QQApiImpl extends AbstractOAuth2ApiBinding implements QQApi {
    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private String appId;
    private String openId;

    public QQApiImpl(String accessToken, String appId) {
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId = appId;
        String url = String.format(URL_GET_OPENID, accessToken);
        String result = getRestTemplate().getForObject(url, String.class);
        log.debug("系统-用户中心-oauth2.0认证-QQ用户OpenID获取返回结果:{}", result);
        //返回数据为: callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
        this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
        log.info("系统-用户中心-oauth2.0认证-获取QQ用户openId成功:{}", openId);
    }

    @Override
    public QQUserInfo getUserInfo() {
        String url = String.format(URL_GET_USERINFO, appId, openId);
        String result = getRestTemplate().getForObject(url, String.class);
        log.debug("系统-用户中心-oauth2.0认证-QQ用户信息获取返回结果:{}", result);
        try {
            QQUserInfo userInfo = JSON.parseObject(result, QQUserInfo.class);
            userInfo.setOpenId(openId);
            log.info("系统-用户中心-oauth2.0认证-获取QQ用户用户信息成功:{}", JSON.toJSONString(userInfo));
            return userInfo;
        } catch (Exception e) {
            throw new RuntimeException("获取用户信息失败", e);
        }
    }
}
